#include "filehandle.h"
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<sys/socket.h>

bool FileHandler::sendFile(int socket, const std::string &filePath) {
    int fd = open(filePath.c_str(), O_RDONLY);
    if (fd < 0) return false;

    struct stat stat_buf;
    fstat(fd, &stat_buf);
    sendfile(socket, fd, nullptr, stat_buf.st_size);
    close(fd);
    return true;
}

bool FileHandler::receiveFile(int socket, const std::string &filePath) {
    std::ofstream file(filePath, std::ios::binary);
    if (!file) return false;

    char buffer[4096];
    ssize_t bytesRead;
    while ((bytesRead = recv(socket, buffer, sizeof(buffer), 0)) > 0) {
        file.write(buffer, bytesRead);
    }
    return true;
}